// pages/index/index.js
import ajax from "../../utils/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    locationType: true, // 是否授权
    bannerList: [], // 轮播列表
    recommendList: [], // 推荐园区列表
    recommendShow: false,
    parkList: [], // 园区列表
    managementList: [], // icon按钮
    topHeight: 0, // 导航栏高度
    location: null, // 定位信息
    formData: {
      queryActive: null, // 查询条件显示状态
      pageSize: 10,
      pageNum: 1,
      parkTotal: 0,
      area: '', // 区 
      adCade: '', // 城市ID
      city: '', //市 
      adCadeCity: '',
      housingAreaMax: '', //房源面积范围 
      housingAreaMin: '', //房源面积范围 
      housingPriceMax: '', //房源价格范围 
      housingPriceMin: '', //房源价格范围 
      kilometre: '', //公里数 
      lat: '', //纬度 
      lng: '', // 经度 
      minimumPrice: '', //最低价格传 1 
      province: '', //省
      search: '', //搜索
      sort: 0, // 排序传 1
    },
    /**
     * 用户信息
     */
    userInfo: {
      roles: null
    },
    pageIndex: null, // 园区组件
    pageStatus: 0, // 页面状态 0 普通首页, 1 园区首页
    gardenRole: [], // 园区及权限列表
    gardenRoleIndex: 0,
    gardenRoleItem: null,
    menusShow: false,
    swiperIndex: 0,
    videoIndex: null, // 当前视频播放状态

  },
  /**
   * 重置事件
   */
  resetEvent() {
    const { city, adCade, adCadeCity } = this.data.formData
    this.setData({
      formData: {
        queryActive: null, // 查询条件显示状态
        pageSize: 10,
        pageNum: 1,
        parkTotal: 0,
        area: '', // 区 
        adCade: adCade || '', // 城市ID
        city: city, //市 
        adCadeCity: adCadeCity || '',
        housingAreaMax: '', //房源面积范围 
        housingAreaMin: '', //房源面积范围 
        housingPriceMax: '', //房源价格范围 
        housingPriceMin: '', //房源价格范围 
        kilometre: '', //公里数 
        lat: '', //纬度 
        lng: '', // 经度 
        minimumPrice: '', //最低价格传 1 
        province: '', //省
        search: '', //搜索
        sort: 0, // 排序传 1
      }
    })
  },
  homeIconEvent (event) {
    const item = event.currentTarget.dataset.item
    wx.navigateTo({
      url: item.jumpAddress,
      fail: () => ajax.showToast('开发中...')
    })
  },
  cityEvent() {
    const { formData } = this.data
    wx.navigateTo({
      url: `/pages/citySelect/citySelect?city=${formData.city}`,
      events: {
        backEvent: (res) => {
          formData.city = res.regionName
          formData.adCadeCity = res.id
          formData.area = ''
          this.setData({ formData })
          this.queryEvent()
          this.getHomeIcon()
          this.getRecommendParkList()
        }
      }
    })
  },
  homeQueryActivEvent(event) {
    this.setData({ 'formData.queryActive': event.detail || null })
  },
  queryActiveEvent(event) {
    const queryActive = event.currentTarget.dataset.index
    this.data.formData.queryActive = queryActive
    this.setData({ formData: this.data.formData })
  },
  /**
   * 查询条件赋值
   */
  homeQueryEvent(event) {
    const formData = Object.assign(this.data.formData, event.detail)
    formData.queryActive = null
    this.setData({ formData })
    this.queryEvent()
  },
  videoEvent(event) {
    console.log(event)
    this.setData({
      videoIndex: event.currentTarget.dataset.index
    })
  },
  recommendSwiperChange(event) {
    this.setData({ swiperIndex: event.detail.current })
  },
  menusShowEvent() {
    this.setData({ menusShow: true })
  },
  menusCancel() {
    this.setData({ menusShow: false })
  },
  gardenRoleEvent(event) {
    const { index, item } = event.currentTarget.dataset;
    if (this.data.gardenRoleItem.id == item.id) return
    wx.setStorageSync('gardenRoleItem', item)
    this.setData({ gardenRoleItem: item, gardenRoleIndex: index })
    this.data.pageIndex.infoRequest()
    this.menusCancel()
  },
  /**
   * 筛选条件查询
   */
  queryEvent(event) {
    this.data.formData.pageNum = 1
    this.getParkList()
  },
  /**
   * 搜索input变化事件
   */
  searchInputChange(event) {
    this.setData({ 'formData.search': event.detail.value })
  },
  /**
   * 获取首页 按钮
   */
  async getHomeIcon() {
    const { formData, userInfo } = this.data
    const res = await ajax.get(`/wx/management/list?city=${formData.city}&wxUserId=${userInfo?.id || ''}`)
    const list = ajax.listFormat(res.rows, 4)
    this.setData({ managementList: list })
  },
  /**
   * 获取园区列表
   */
  async getParkList() {
    const { formData, parkList } = this.data
    const res = await ajax.get('/enterpriseservice/home/gardenkHousingList', formData).finally(() => wx.stopPullDownRefresh());
    this.data.formData.parkTotal = res.total - 0
    res.rows.forEach(item => {
      const key = item.gardenLabel ? item.gardenLabel.indexOf('；') != -1 ? '；' : item.gardenLabel.indexOf(';') != -1 ? ';' : '' : '';
      item.gardenLabel = item.gardenLabel ? item.gardenLabel.split(key) : []
    })
    this.setData({ parkList: formData.pageNum == 1 ? res.rows : parkList.concat(res.rows) })
  },

  /**
    * 获取园区推荐
    */
  async getRecommendParkList() {
    const res = await ajax.get(`/enterpriseservice/home/recommend?city=${this.data.formData.city}`)
    const list = res.rows
    this.setData({ recommendList: list })
  },
  /**
   * 获取定位授权
   */
  async getLocation() {
    const { formData } = this.data
    const res = await ajax.getLocationQQMap()
    this.data.location = res
    formData.city = res.city
    formData.adCade = res.adcode
    this.setData({ locationType: res.type, formData })
  },

  /**
   * 获取轮播图
   */
  async getBannerList() {
    const res = await ajax.get('/enterpriseservice/home/rotation/list?type=1');
    this.setData({ bannerList: res.rows })
  },


  /**
   * 初始化接口调用函数
   */
  async infoRequest(type) {
    this.resetEvent()
    type ? null : await this.getLocation()
    this.getHomeIcon()
    this.getParkList()
    this.getBannerList()
    this.getRecommendParkList()
    this.setData({ topHeight: ajax.getHeadlineHeight() })
  },
  /**
   * 用户信息
   */
  async getUserInfo() {
    const userInfo = await ajax.getUserInfo({ isLogin: true })
    this.setData({ userInfo: userInfo || { roles: null } })
  },

  /**
   * 园区及权限列表
   */
  async getGardenRole() {
    let { gardenRole, gardenRoleIndex, gardenRoleItem } = this.data
    const res = await ajax.get('/gardenRole/list');
    gardenRole = res.rows
    gardenRoleItem = gardenRole[gardenRoleIndex] || null
    wx.setStorageSync('gardenRoleItem', gardenRoleItem)
    this.setData({ gardenRole, gardenRoleItem })
    this.data.pageIndex.infoRequest()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ topHeight: ajax.getHeadlineHeight() })
    this.infoRequest()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserInfo()
    const pageRoles = wx.getStorageSync('pageRoles') || 0;
    this.setData({ pageStatus: pageRoles })
    if (pageRoles == 1) {
      this.data.pageIndex = this.selectComponent('#pageIndex')
      this.getGardenRole();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({ videoIndex: null })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.pageStatus == 1) {
      this.getGardenRole()
    }
    this.getUserInfo()
    const { formData } = this.data
    formData.pageNum = 1;
    this.setData({ formData })
    this.infoRequest(1)
    this.queryEvent()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { formData, parkList } = this.data
    if (formData.parkTotal == parkList.length) return
    this.data.formData.pageNum += 1;
    this.getParkList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let shareContent = this.data.shareContent
    // console.log(shareContent)
    return {
      title: '(' + shareContent.houseArea + '㎡' + shareContent.fitmentCase + ')' + shareContent.gardenName,
      imageUrl: shareContent.houseImg,
      path: '/pages/park/park?id=' + shareContent.gardenId + '&inviterUserId=' + app.globalData.userInfo.id
    }
  }
})